package baoxin.com.robotcoach;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.VideoView;

import java.util.ArrayList;
import java.util.List;

import baoxin.com.robotcoach.adapter.VideoAdapter;
import baoxin.com.robotcoach.bean.Video;
import baoxin.com.robotcoach.interfaces.VideoClick;
import baoxin.com.robotcoach.utils.MyLog;
import baoxin.com.robotcoach.utils.MyToast;

public class VideoListActivity extends BaseActivity implements View.OnClickListener, VideoClick {

    RecyclerView video_list_view;
    MediaMetadataRetriever mmr;
    List<Video> videoList;

    private ImageView mVideoFront;
    private VideoView mVideoView;//视频控件
    private ImageView mBigPlayBtn;//大的播放按钮
    private ImageView mPlayBtn;//播放按钮
    private ImageView mFullScreenBtn;//全屏按钮
    private SeekBar mPlayProgressBar;//播放进度条
    private TextView mPlayTime;//播放时间

    private String path = null;//视频path----
    private int videoDuration;//视频毫秒数
    private int mCurrentProgress;//当前毫秒数----------

    private ImageView mDetailThumbnail;
    private TextView mDetailTitle;
    private TextView mDetailContent;

    private Runnable mUpdateTask;
    private Thread mUpdateThread;

    private final int UPDATE_PROGRESS = 0;
    private final int EXIT_CONTROL_PANEL = 1;
    private boolean stopThread = true;//停止更新进度线程标志
    public static final int FULL_SCREEN_FINISH = 100;
    public static final int FULL_SCREEN = 101;


    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE_PROGRESS:
                    mPlayProgressBar.setProgress(mCurrentProgress);
                    setPlayTime(mCurrentProgress);
                    break;
                case EXIT_CONTROL_PANEL:
                    setControlPanelStatus(View.GONE);
                    break;

            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_list);

        mmr = new MediaMetadataRetriever();

        initData();

        initView();


    }

    private void initView() {
        video_list_view = findViewById(R.id.video_list);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        VideoAdapter videoAdapter = new VideoAdapter(videoList);
        videoAdapter.setListener(this);
        video_list_view.setLayoutManager(layoutManager);
        video_list_view.setAdapter(videoAdapter);

        mVideoFront = findViewById(R.id.video_front);
        mBigPlayBtn = findViewById(R.id.big_play_button);
        mPlayBtn = findViewById(R.id.play_button);
        mFullScreenBtn = findViewById(R.id.full_screen_button);
        mPlayProgressBar = findViewById(R.id.progress_bar);
        mPlayTime = findViewById(R.id.play_time);
        mVideoView = findViewById(R.id.video_view);

        mBigPlayBtn.setOnClickListener(this);
        mPlayBtn.setOnClickListener(this);
        mFullScreenBtn.setOnClickListener(this);

        mBigPlayBtn.setVisibility(View.VISIBLE);


        prepareToPlay(videoList.get(0));

        mDetailThumbnail = findViewById(R.id.detail_thumbnail);
        mDetailTitle = findViewById(R.id.detail_title);
        mDetailContent = findViewById(R.id.detail_content);
    }

    private void prepareToPlay(final Video video) {
//        if (mVideoView.isPlaying()) {
//            mVideoView.pause();
//            mBigPlayBtn.setVisibility(View.VISIBLE);
//        }
        path = video.getPath();
        mVideoView.setVideoURI(Uri.parse(path));
        mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                initControlInfo(video);
            }
        });

        mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mVideoView.seekTo(0);
                mPlayProgressBar.setProgress(0);
                mPlayBtn.setImageResource(R.drawable.play);
                mBigPlayBtn.setVisibility(View.VISIBLE);
                setPlayTime(0);
                stopThread = true;
            }
        });
    }

    private void initControlInfo(Video video) {
        path = video.getPath();
        videoDuration = mVideoView.getDuration();
        mPlayTime.setText("00:00/" + formatTime(videoDuration));
        mPlayProgressBar.setMax(videoDuration);
        mPlayProgressBar.setProgress(0);

        mUpdateTask = new Runnable() {
            @Override
            public void run() {
                while (!stopThread) {
                    mCurrentProgress = mVideoView.getCurrentPosition();//获取进度
                    handler.sendEmptyMessage(UPDATE_PROGRESS);
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };

        mVideoFront.setOnClickListener(this);

        mPlayProgressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    mVideoView.seekTo(progress);
                    setPlayTime(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                handler.removeMessages(EXIT_CONTROL_PANEL);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                handler.sendEmptyMessageDelayed(EXIT_CONTROL_PANEL, 300);
            }
        });

        mDetailThumbnail.setBackground(video.getThumbnail());
        mDetailTitle.setText(video.getTitle());
        mDetailContent.setText(video.getContent());

    }

    private void initData() {
        videoList = new ArrayList<>();

        String path = "android.resource://" + getPackageName() + "/" + R.raw.keerquxian;
        Video video = new Video();
        video.setPath(path);
        video.setTitle("曲线行驶");
        video.setContent("规定宽度S型路面驾驶技巧");
        video.setTime(getTime(path));
        video.setThumbnail(getThumbnail(path));
        videoList.add(video);

        String path2 = "android.resource://" + getPackageName() + "/" + R.raw.keercefang;
        Video video2 = new Video();
        video2.setPath(path2);
        video2.setTitle("侧方位停车");
        video2.setContent("侧后方倒车入库驾驶技巧");
        video2.setTime(getTime(path2));
        video2.setThumbnail(getThumbnail(path2));
        videoList.add(video2);

        String path3 = "android.resource://" + getPackageName() + "/" + R.raw.keerpodao;
        Video video3 = new Video();
        video3.setPath(path3);
        video3.setTitle("坡道定点");
        video3.setContent("离合器刹车之间半联动技巧");
        video3.setTime(getTime(path3));
        video3.setThumbnail(getThumbnail(path3));
        videoList.add(video3);

        String path4 = "android.resource://" + getPackageName() + "/" + R.raw.keerzhijiao;
        Video video4 = new Video();
        video4.setPath(path4);
        video4.setTitle("直角转弯");
        video4.setContent("规定路线转弯的驾驶技巧");
        video4.setTime(getTime(path4));
        video4.setThumbnail(getThumbnail(path4));
        videoList.add(video4);

        String path5 = "android.resource://" + getPackageName() + "/" + R.raw.keerruku;
        Video video5 = new Video();
        video5.setPath(path5);
        video5.setTitle("倒车入库");
        video5.setContent("指定时间停车入库的能力");
        video5.setTime(getTime(path5));
        video5.setThumbnail(getThumbnail(path5));
        videoList.add(video5);

    }

    public void onBack(View view) {
        finish();
        String path2 = "android.resource://" + getPackageName() + "/" + R.raw.keercefang;
        MyToast.show(this, getTime(path2));
    }


    private Drawable getThumbnail(String videoPath) {
        Uri uri = Uri.parse(videoPath);
        mmr.setDataSource(this, uri);
        Bitmap bitmap = mmr.getFrameAtTime();
        return new BitmapDrawable(getResources(), bitmap);
    }

    private String getTime(String videoPath) {
        Uri uri = Uri.parse(videoPath);
        mmr.setDataSource(this, uri);
        String duration = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
        long time = Integer.parseInt(duration);
        return formatTime(time);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mmr.release();
        mVideoView.suspend();
    }

    private void setControlPanelStatus(int status) {
        mPlayBtn.setVisibility(status);
        mFullScreenBtn.setVisibility(status);
        mPlayProgressBar.setVisibility(status);
        mPlayTime.setVisibility(status);
    }

    private void setPlayTime(int millisSecond) {
        mPlayTime.setText(formatTime(millisSecond) + "/" + formatTime(videoDuration));

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.video_front:
                setControlPanelStatus(View.VISIBLE);
                break;
            case R.id.big_play_button:
                mBigPlayBtn.setVisibility(View.GONE);
                if (!mVideoView.isPlaying()) {

                    mPlayBtn.setImageResource(R.drawable.stop);
                    mUpdateThread = new Thread(mUpdateTask);
                    stopThread = false;
                    mUpdateThread.start();
                    mVideoView.start();
                }
                break;
            case R.id.play_button:
                if (mVideoView.isPlaying()) {
                    mVideoView.pause();
                    mPlayBtn.setImageResource(R.drawable.play);

                } else {
                    if (mUpdateThread == null || !mUpdateThread.isAlive()) {
                        mUpdateThread = new Thread(mUpdateTask);
                        stopThread = false;
                        mUpdateThread.start();
                    }
                    mVideoView.start();
                    mPlayBtn.setImageResource(R.drawable.stop);
                    mBigPlayBtn.setVisibility(View.GONE);
                }
                break;
            case R.id.full_screen_button:
                if (mVideoView.isPlaying()) {
                    mVideoView.pause();
                    mPlayBtn.setImageResource(R.drawable.play);

                }
                setFullScreen();

                break;
        }
    }

    public void setFullScreen() {
        Intent it = new Intent(VideoListActivity.this, FullScreenActivity.class);
        it.putExtra("path", path);
        it.putExtra("currentProgress", mCurrentProgress);
        startActivityForResult(it, FULL_SCREEN);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        MyToast.show(this, "resultCode =" + resultCode);
        if (requestCode == FULL_SCREEN && resultCode == FULL_SCREEN_FINISH) {
            mCurrentProgress = data.getIntExtra("currentProgress", mCurrentProgress);
            mPlayProgressBar.setProgress(mCurrentProgress);
            mVideoView.seekTo(mCurrentProgress);
        }
    }

    //计算视频时长,return 01:20
    private String formatTime(long ms) {
        int s = 1000;
        int m = s * 60;
        long minute = ms / m;
        long second = (ms - m * minute) / s;
        if (minute > 10) {
            if (second > 10) {
                return minute + ":" + second;
            } else {
                return minute + ":0" + second;
            }

        } else {
            if (second > 10) {
                return "0" + minute + ":" + second;
            } else {
                return "0" + minute + ":0" + second;
            }
        }
    }

    @Override
    public void play(Video video) {
        prepareToPlay(video);
    }
}
